<?php

namespace app\api\controller;

use addons\wechat\library\Wechat;
use addons\wechat\model\WechatCaptcha;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Http;
use fast\Random;
use think\Validate;

/**
 * 定时任务
 */
class Task extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 结算课时
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function curriculum()
    {
        $date = date('Y-m-d');

        /**
         * 查询班级排课表
         *
         */
        $schedule_list = db('school_class_subject_schedule')
            ->alias('a')
            ->field('a.*,b.remind,d.subject_name')
            ->join('ed_school_class b', 'b.id = a.class_id', 'left')
            ->join('ed_school_class_subject c', 'c.id = a.class_subject_id', 'left')
            ->join('ed_school_subject d', 'd.id = c.subject_id', 'left')
            ->whereTime('a.date', '<=', $date)
            ->where('a.status', '0')
            ->where('b.status', '0')
            ->select();


        foreach ($schedule_list as $k => $v) {
            $time_slot = explode('-', $v['time_slot']);
            $time_string = $v['date'] . ' ' . $time_slot[1];
            $stime = strtotime($time_string);
            if ($stime < time()) {
                $sheet_list = db('school_user_attendance_sheet')
                    ->where('subject_schedule_id', $v['id'])
                    ->select();
                $sheet_list_user_id = [];
                $sheet_list_user_id = array_column($sheet_list, 'user_id');
                db('school_calss_user')
                    ->alias('a')
                    ->where('a.class_id', $v['class_id'])
                    ->where('a.status', '0')
                    ->where('user_id', 'notin', $sheet_list_user_id)
                    ->setInc('use_class_hour');
                db('school_class_subject')
                    ->alias('a')
                    ->where('a.id', $v['class_subject_id'])
                    ->setInc('use_class_hour');
                $calss_user = db('school_calss_user')
                    ->alias('a')
                    ->where('a.class_id', $v['class_id'])
                    ->where('a.status', '0')
                    ->where('user_id', 'notin', $sheet_list_user_id)
                    ->select();
                $sheet_data = [];
                $dataLog = [];
                foreach ($calss_user as $vv) {
                    $dataLog[] = [
                        'admin_id' => 0,
                        'user_id' => $vv['user_id'],
                        'create_time' => time(),
                        'content' => '上课（' . $v['subject_name'] . $v['da    te'] . '）结算课时1'
                    ];
                    $sheet_data[] = [
                        'user_id' => $vv['user_id'],
                        'class_id' => $v['class_id'],
                        'subject_schedule_id' => $v['id'],
                        'class_subject_id' => $v['class_subject_id'],
                        'createtime' => time()
                    ];
                    $this->coupon($vv['user_id']);
                }
                db('SchoolUserLog')->insertAll($dataLog);
                db('school_user_attendance_sheet')->insertAll($sheet_data);
                db('school_class_subject_schedule')->where('id', $v['id'])->update(['status' => '1']);
            }
        }
    }

    /**
     * 课时卷结算
     */
    public function coupon($user_id = 1)
    {
        $school_coupon = db('school_coupon')
            ->where('user_id', $user_id)
            ->where('status', '0')
            ->order('end_time', 'asc')
            ->find();
        if ($school_coupon) {
            $data = [];
            $data['da_condition'] = $school_coupon['da_condition'] + 1;
            if ($school_coupon['condition'] == ($school_coupon['da_condition'] + 1)) {
                $data['status'] = 1;
                db('user')->where('id', $user_id)->setInc('discount_amount');
                $dataLog[] = [
                    'admin_id' => 0,
                    'user_id' => $user_id,
                    'create_time' => time(),
                    'content' => '激活课时卷，优惠课时+1'
                ];
                db('SchoolUserLog')->insertAll($dataLog);
            }
            //存在课时卷时
            db('school_coupon')
                ->where('id', $school_coupon['id'])
                ->update($data);
        }
    }

    /**
     * 课前通知
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function notice()
    {
        $date = date('Y-m-d');
        $schedule_list = db('school_class_subject_schedule')
            ->alias('a')
            ->field('a.*,b.remind,b.admin_id,d.subject_name')
            ->join('ed_school_class b', 'b.id = a.class_id', 'left')
            ->join('ed_school_class_subject c', 'c.id = a.class_subject_id', 'left')
            ->join('ed_school_subject d', 'd.id = c.subject_id', 'left')
            ->where('b.status', '0')
            ->where('a.date', $date)
            ->where('is_notice', 0) 
            ->select();
        //print_r($schedule_list);
        //return;
        foreach ($schedule_list as $k => $v) {
            if ($v['remind']) {
                $time_slot = explode('-', $v['time_slot']);
                $stime = strtotime($time_slot[0]) - (60 * 60 * $v['remind']);
                if ($stime < time() && strtotime($time_slot[0]) > time()) {
                    print_r(strtotime($time_slot[0]));
                    $calss_user = db('school_calss_user')
                        ->alias('a')
                        ->field('b.*,c.nickname')
                        ->join('ed_third b', 'b.user_id = a.user_id', 'right')
                        ->join('ed_user c', 'c.id = b.user_id', 'left')
                        ->where('a.class_id', $v['class_id'])
                        ->where('a.status', '0')
                        ->select();
                    $admin_third = db('third')->where('admin_id', $v['admin_id'])->find();
                    $this->send($admin_third['openid'], $v['subject_name'], $time_slot[0], $v['remind']);
                    foreach ($calss_user as $vv) {
                        $this->send($vv['openid'], $v['subject_name'], $time_slot[0], $v['remind']);
                    }
                    db('school_class_subject_schedule')->where('id', $v['id'])->update(['is_notice' => 1]);
                }
            }
        }
        $this->success('成功');
        /**return;
         * if ($result['ret']) {
         * $this->success($result);
         * }
         * $this->error("获取失败！请稍后重试"); */
    }

    /**
     * @param $touser open_id
     * @param $name 课程名
     * @param $ye 参加人
     * @param $h 提前小时
     * @return array
     */
    public function send($touser, $name, $date, $h)
    {
        $token = Wechat::getAccessToken();
        if (!$token) {
            $this->error("发送失败，请稍后重试");
        }

        $url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . $token;
        $params = [
            'touser' => $touser,
            'template_id' => 'v2BwBzImoHdC5C5oFcSsywMIKl8tjvkVLZYRpqgXGAk',
            'data' => [
                'first' => ['value' => '你好，以下课程将在' . $h . '小时后开始.', 'color' => '#173177'],
                'keyword1' => ['value' => $name, 'color' => '#173177'],
                'keyword2' => ['value' => $date, 'color' => '#173177'],
                'keyword3' => ['value' => '线下', 'color' => '#173177'],
                'keyword4' => ['value' => '暂无', 'color' => '#173177'],
                'remark' => ['value' => '若因故无法参加，请及时联系老师', 'color' => '#173177']
            ]
        ];

        return $result = Http::sendRequest($url, json_encode($params));
    }
}
